package cn.itcast.bos.service.system.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.system.MenuRepository;
import cn.itcast.bos.dao.system.PermissionRepository;
import cn.itcast.bos.dao.system.RoleRepository;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServieImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;
	
	@Autowired
	private PermissionRepository permissionRepository;
	
	@Autowired
	private MenuRepository menuRepository;
	
	@Override
	public List<Role> findByUser(User user) {
		//基于用户查询角色
		//admin赋予所有角色
		if(user.getUsername().equals("admin")) {
			return roleRepository.findAll();
		}else {
			return roleRepository.findByUser(user.getId());
		}
	}

	@Override
	public List<Role> findAll() {
		return roleRepository.findAll();
	}


	@Override
	public void save(Role role, String[] permissionIds, String menuIds) {
		
		//这里的角色,需要关联菜单和权限
		if(permissionIds != null){
			//对数组permisssion进行遍历,查询得到所有的权限对象,将所有的权限对象与role进行关联
			for (String permissionId : permissionIds) {
				Permission p = permissionRepository.findOne(Integer.parseInt(permissionId));
				role.getPermissions().add(p);
			}
		}
		
		if(StringUtils.isNotBlank(menuIds)){
			String[] menuIdArray = menuIds.split(",");
			for (String menuId : menuIdArray) {
				Menu m = menuRepository.findOne(Integer.parseInt(menuId));
				role.getMenus().add(m);
			}
		}
		
		//保存role
		roleRepository.save(role);
	}
}
